// 待办事项类
class TodoItem {
	constructor(id, text, completed = false) {
		this.id = id;
		this.text = text;
		this.completed = completed;
		this.createdAt = new Date();
	}
}

// 待办事项管理类
class TodoApp {
	constructor() {
		this.todos = [];
		this.currentFilter = "all";
		this.nextId = 1;

		// 初始化DOM元素引用
		this.todoInput = document.querySelector(".todo-input");
		this.addButton = document.querySelector(".add-btn");
		this.filterButtons = document.querySelectorAll(".filter-btn");
		this.todoList = document.querySelector(".todo-list");
		this.statsElement = document.querySelector(".stats");

		// 初始化事件监听
		this.initEventListeners();

		// 从本地存储加载数据
		this.loadFromLocalStorage();

		// 渲染初始列表
		this.renderTodos();
	}

	initEventListeners() {
		// 添加按钮点击事件
		this.addButton.addEventListener("click", () => this.addTodo());

		// 输入框回车事件
		this.todoInput.addEventListener("keypress", (e) => {
			if (e.key === "Enter") {
				this.addTodo();
			}
		});

		// 过滤器按钮点击事件
		this.filterButtons.forEach((button) => {
			button.addEventListener("click", (e) => {
				this.setFilter(e.target.dataset.filter);
			});
		});
	}

	addTodo() {
		const text = this.todoInput.value.trim();
		if (text === "") return;

		const todo = new TodoItem(this.nextId++, text);
		this.todos.push(todo);

		// 清空输入框
		this.todoInput.value = "";

		// 保存到本地存储
		this.saveToLocalStorage();

		// 重新渲染列表
		this.renderTodos();
	}

	toggleTodo(id) {
		const todo = this.todos.find((t) => t.id === id);
		if (todo) {
			todo.completed = !todo.completed;

			// 保存到本地存储
			this.saveToLocalStorage();

			// 重新渲染列表
			this.renderTodos();
		}
	}

	deleteTodo(id) {
		const todoElement = document.querySelector(`[data-id="${id}"]`);

		// 添加删除动画
		if (todoElement) {
			todoElement.classList.add("removing");

			// 动画结束后删除
			setTimeout(() => {
				this.todos = this.todos.filter((t) => t.id !== id);

				// 保存到本地存储
				this.saveToLocalStorage();

				// 重新渲染列表
				this.renderTodos();
			}, 300);
		}
	}

	setFilter(filter) {
		this.currentFilter = filter;

		// 更新活动按钮
		this.filterButtons.forEach((button) => {
			if (button.dataset.filter === filter) {
				button.classList.add("active");
			} else {
				button.classList.remove("active");
			}
		});

		// 重新渲染列表
		this.renderTodos();
	}

	getFilteredTodos() {
		switch (this.currentFilter) {
			case "active":
				return this.todos.filter((todo) => !todo.completed);
			case "completed":
				return this.todos.filter((todo) => todo.completed);
			default:
				return this.todos;
		}
	}

	renderTodos() {
		const filteredTodos = this.getFilteredTodos();

		// 更新统计信息
		this.updateStats();

		// 清空列表
		this.todoList.innerHTML = "";

		if (filteredTodos.length === 0) {
			// 显示空状态
			const emptyState = document.createElement("div");
			emptyState.className = "empty-state";

			let message = "";
			if (this.todos.length === 0) {
				message = "<p>暂无待办事项</p><p>添加一个新任务开始吧</p>";
			} else if (this.currentFilter === "active") {
				message = "<p>暂无未完成的待办事项</p>";
			} else if (this.currentFilter === "completed") {
				message = "<p>暂无已完成的待办事项</p>";
			} else {
				message = "<p>暂无待办事项</p><p>添加一个新任务开始吧</p>";
			}

			emptyState.innerHTML = message;
			this.todoList.appendChild(emptyState);
			return;
		}

		// 渲染待办事项
		filteredTodos.forEach((todo) => {
			const todoElement = document.createElement("div");
			todoElement.className = "todo-item";
			todoElement.dataset.id = todo.id;

			todoElement.innerHTML = `
                        <input type="checkbox" class="todo-checkbox" ${
													todo.completed ? "checked" : ""
												}>
                        <span class="todo-text ${
													todo.completed ? "completed" : ""
												}">${todo.text}</span>
                        <button class="delete-btn">×</button>
                    `;

			// 添加事件监听
			const checkbox = todoElement.querySelector(".todo-checkbox");
			checkbox.addEventListener("change", () => this.toggleTodo(todo.id));

			const deleteBtn = todoElement.querySelector(".delete-btn");
			deleteBtn.addEventListener("click", () => this.deleteTodo(todo.id));

			this.todoList.appendChild(todoElement);
		});
	}

	updateStats() {
		const total = this.todos.length;
		const active = this.todos.filter((todo) => !todo.completed).length;

		this.statsElement.textContent = `${active}个未完成，${total}个总计`;
	}

	saveToLocalStorage() {
		localStorage.setItem("todos", JSON.stringify(this.todos));
		localStorage.setItem("nextId", this.nextId.toString());
	}

	loadFromLocalStorage() {
		const savedTodos = localStorage.getItem("todos");
		const savedNextId = localStorage.getItem("nextId");

		if (savedTodos) {
			this.todos = JSON.parse(savedTodos);
		}

		if (savedNextId) {
			this.nextId = parseInt(savedNextId);
		}
	}
}

// 初始化应用
document.addEventListener("DOMContentLoaded", () => {
	new TodoApp();
});
